package cn.com.thingo.shyintelligent.ui.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.th.opensdk.openapi.NotificationInfo;
import com.th.opensdk.openapi.THOpenSDK;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.shyintelligent.R;
import cn.com.thingo.shyintelligent.app.App;
import cn.com.thingo.shyintelligent.base.BaseActivity;
import cn.com.thingo.shyintelligent.base.contract.SelectGatewayContract;
import cn.com.thingo.shyintelligent.model.bean.GatewayListBean;
import cn.com.thingo.shyintelligent.presenter.SelectGatewayPresenter;
import cn.com.thingo.shyintelligent.ui.adapter.GatewayListAdapter;
import cn.com.thingo.shyintelligent.ui.adapter.decoration.RecycleViewDivider;
import cn.com.thingo.shyintelligent.ui.receiver.THOpenReceiver;
import cn.com.thingo.shyintelligent.util.SPUtils;
import cn.com.thingo.shyintelligent.util.ToastUtil;

public class SelectGatewayActivity extends BaseActivity<SelectGatewayPresenter> implements SelectGatewayContract.View
        , GatewayListAdapter.OnItemClickListener {
    @BindView(R.id.toolbar_left)
    ImageView ivToolbarLeft;
    @BindView(R.id.toolbar_title)
    TextView tvTitle;
    @BindView(R.id.select_gateway_list)
    RecyclerView rvGatewayList;
    @BindView(R.id.login_hint)
    View loginProgress;

    private List<GatewayListBean.DataBean> gatewayList = new ArrayList<>();
    private GatewayListAdapter adapter;
    private THOpenReceiver receiver;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    gatewayConnectFail();
                    App.getInstance().setGatewayLoginStatus(true);
                    break;
            }
        }
    };

    @Override
    protected int getLayout() {
        return R.layout.activity_select_gateway;
    }

    @Override
    protected void initEventAndData() {
        ivToolbarLeft.setImageResource(R.mipmap.no);
        tvTitle.setText(R.string.select_gateway);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.gatewayList(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
        registerReceiver();
    }

    private void initView() {
        adapter = new GatewayListAdapter(gatewayList, mContext);
        adapter.setListener(this);
        rvGatewayList.setLayoutManager(new LinearLayoutManager(mContext));
        rvGatewayList.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.gray_12)));
        rvGatewayList.setAdapter(adapter);
    }


    @Override
    public void onItemClick(int position) {
        if (App.getInstance().isGatewayLoginStatus()) {
            App.getInstance().setGatewayLoginStatus(false);
            final GatewayListBean.DataBean dataBean = gatewayList.get(position);
            //授权
            loginProgress.setVisibility(View.VISIBLE);
            SPUtils.newInstance().put(SPUtils.GATEWAY_CURRENT, dataBean.getNumber());
            SPUtils.newInstance().put(SPUtils.GATEWAY_CURRENT_NAME, dataBean.getTitle());
//            SPUtils.newInstance().put(SPUtils.GATEWAY_IS_CREATE, dataBean.getIs_creat());
            new Thread() {
                @Override
                public void run() {
                    App.setDataBean(dataBean);
                    int i = THOpenSDK.getInstance().loginGateway(dataBean.getNumber(), dataBean.getUsername(), dataBean.getPassword());
                    if (i != 0) {
                        handler.sendEmptyMessage(1);
                    }
                }
            }.start();
        } else {
            ToastUtil.shortShow("正在登录网关...");
        }
    }

    //隐藏登录的进度条
    public void hideProgress() {
        loginProgress.setVisibility(View.GONE);
    }

    public void gatewayConnectFail() {
        ToastUtil.shortShow("登录失败，请检查网关！");
        hideProgress();
    }

    private void registerReceiver() {
        receiver = new THOpenReceiver(SelectGatewayActivity.this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(NotificationInfo.BROADCAST_GATEWAY_STATUS_CHANGED);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }


    // 添加网关的点击回调
    @Override
    public void addGateway() {
        Intent intent = new Intent(SelectGatewayActivity.this, AddGatewayActivity.class);
        startActivity(intent);
    }

    @Override
    public void viewGatewayList(GatewayListBean gatewayListBean) {
        List<GatewayListBean.DataBean> data = gatewayListBean.getData();
        gatewayList.clear();
        if (data != null && data.size() > 0) {
            gatewayList.addAll(data);
        }
        adapter.notifyDataSetChanged();
    }

    @OnClick({R.id.toolbar_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left:
                finish();
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);
    }
}
